package com.lzh.sms.sms;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.google.gson.Gson;
import com.lzh.sms.enums.AliyunSmsApiErrorCode;
import com.lzh.sms.exceptions.VinusException;
import com.lzh.sms.props.AliYunSMSProperty;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.util.Map;

/**
 * @author zhehen.lu
 * @date 2025/8/14 17:05
 */
public class SmsComponent {
    private Gson gson;

    private AliYunSMSProperty aliYunSMSProperty;

    private final Log logger = LogFactory.getLog(getClass());

    public SmsComponent(Gson gson, AliYunSMSProperty aliYunSMSProperty) {
        this.gson = gson;
        this.aliYunSMSProperty = aliYunSMSProperty;
    }

    public SmsComponent() {
    }

    public void doSendSms(String phone, String smsSignature, String templateCode, Map<String, String> map) {
        IClientProfile profile = DefaultProfile.getProfile(aliYunSMSProperty.getRegionId(),
                aliYunSMSProperty.getAccessKeyId(), aliYunSMSProperty.getSecret());
        try {
            DefaultProfile.addEndpoint(aliYunSMSProperty.getEndPoint(), aliYunSMSProperty.getRegionId(),
                    aliYunSMSProperty.getProduct());
            IAcsClient client = new DefaultAcsClient(profile);
            SendSmsRequest request = new SendSmsRequest();
            request.setSysMethod(MethodType.POST);
            request.setSignName(smsSignature);
            request.setTemplateCode(templateCode);
            request.setTemplateParam(gson.toJson(map));
            request.setPhoneNumbers(phone);
            request.setSysConnectTimeout((int) aliYunSMSProperty.getConnectionTimeout().toMillis());
            request.setSysReadTimeout((int) aliYunSMSProperty.getReadTimeout().toMillis());
            if (logger.isDebugEnabled()) {
                logger.debug(String.format("准备开始发送短信：%s——%s——%s", phone, templateCode, map.toString()));
            }
            SendSmsResponse httpResponse = client.getAcsResponse(request);
            if (!"OK".equals(httpResponse.getCode())) {
                throw new VinusException("短信验证码出错：" + AliyunSmsApiErrorCode.getMessage(httpResponse.getCode()));
            }
        } catch (ClientException e) {
            throw new VinusException("短信验证码出错：" + e.getMessage());
        }
    }
}
